package com.yrh.dao.impl;

import com.yrh.bean.TCart;
import com.yrh.dao.TCartDao;
import com.yrh.utils.DataSourceUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

/*购物车数据层接口实现类*/
public class TCartDaoImpl implements TCartDao {
    //创建jdbc操作类
    private JdbcTemplate temp = new JdbcTemplate(DataSourceUtil.getDataSource());

    /*查询购物车*/
    @Override
    public List<TCart> allCart(TCart cart) {
        if (cart.getProductId()!=0&&!"".equals(cart.getProductId()))
        return temp.query("select * from t_cart where product_id=? and user_id=?", new BeanPropertyRowMapper<>(TCart.class), cart.getProductId(),
                cart.getUserId());
        else { //直接点击购物车
            return temp.query("SELECT c.*,p.product_name,p.product_pic,p.product_price \n" +
                    "FROM t_cart c,t_product p \n" +
                    "WHERE p.product_id=c.product_id AND user_id=?",new BeanPropertyRowMapper<>(TCart.class),cart.getUserId());
        }
    }

    /*修改或添加购物车*/
    @Override
    public int save(TCart tCart) {
        //购物车中存在该商品 修改商品数量
        if (tCart.getCartId() != 0 && !"".equals(tCart.getCartId())) {
            return temp.update("UPDATE t_cart \n" +
                    "SET product_num=? \n" +
                    "WHERE cart_id=? ",tCart.getProductNum(),tCart.getCartId());
        } else { //添加到购物车当中
            return  temp.update("insert into t_cart(product_id, product_num, user_id) VALUES(?,1,?)"
            ,tCart.getProductId(),tCart.getUserId());
        }
    }
   //删除购物车
    @Override
    public int deleteCart(TCart tCart) {
        if (tCart.getCartId()!=0&&!"".equals(tCart.getCartId())){
            return temp.update("delete from t_cart where cart_id=?",tCart.getCartId());
        }
//  清空购物车
        return temp.update("delete from t_cart where user_id=?",tCart.getUserId());
    }
}
